//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

class Main extends eui.UILayer {
    /**
     * 加载进度界面
     * loading process interface
     */
    private loadingView: LoadingUI;
    protected createChildren(): void {
        super.createChildren();
        egret.ImageLoader.crossOrigin = "anonymous";
        // if (!window.localStorage.getItem("score_type")) {
        //     window.localStorage.setItem("score_type", "1");
        // }
        // if (!window.localStorage.getItem("rule_type")) {
        //     window.localStorage.setItem("rule_type", "1");
        // }
        // if (!window.localStorage.getItem("banker_mode")) {//庄家模式
        //     window.localStorage.setItem("banker_mode", "3");
        // }
        // if (!window.localStorage.getItem("account_id")) {
        //     var dataURL = SoundMenager.urlSearch()//获取地址后面接的参数
        //     if (dataURL && dataURL["member_id"]) {
        //         window.localStorage.setItem("account_id", dataURL["member_id"]);
        //     }
        // }
        // if (!window.localStorage.getItem("ticket_type")) {//房卡模式，要用几张房卡
        //     window.localStorage.setItem("ticket_type", "1");
        // }
        // if (!window.localStorage.getItem("cards")) {//本人有几张房卡
        //     window.localStorage.setItem("cards", "100");
        // }
        //inject the custom material parser
        //注入自定义的素材解析器
        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());
        //Config loading process interface
        //设置加载进度界面
        this.loadingView = new LoadingUI();
        this.stage.addChild(this.loadingView);
        // initialize the Resource loading library
        //初始化Resource资源加载库
        RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.loadConfig("resource/default.res.json", "resource/");
        // tool.GameWebSocket.getSocket();
    }
    /**
     * 配置文件加载完成,开始预加载皮肤主题资源和preload资源组。
     * Loading of configuration file is complete, start to pre-load the theme configuration file and the preload resource group
     */
    private onConfigComplete(event: RES.ResourceEvent): void {
        RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        // load skin theme configuration file, you can manually modify the file. And replace the default skin.
        //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
        let theme = new eui.Theme("resource/default.thm.json", this.stage);
        theme.addEventListener(eui.UIEvent.COMPLETE, this.onThemeLoadComplete, this);

        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
        RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
        RES.loadGroup("preload");
    }
    private isThemeLoadEnd: boolean = false;
    /**
     * 主题文件加载完成,开始预加载
     * Loading of theme configuration file is complete, start to pre-load the 
     */
    private onThemeLoadComplete(): void {
        this.isThemeLoadEnd = true;
        this.createScene();
    }
    private isResourceLoadEnd: boolean = false;
    /**
     * preload资源组加载完成
     * preload resource group is loaded
     */
    private onResourceLoadComplete(event: RES.ResourceEvent): void {
        if (event.groupName == "preload") {
            this.stage.removeChild(this.loadingView);
            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
            RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
            this.isResourceLoadEnd = true;
            this.createScene();
        }
    }
    private createScene() {
        if (this.isThemeLoadEnd && this.isResourceLoadEnd) {
            this.startCreateScene();
        }
    }
    /**
     * 资源组加载出错
     *  The resource group loading failed
     */
    private onItemLoadError(event: RES.ResourceEvent): void {
        console.warn("Url:" + event.resItem.url + " has failed to load");
    }
    /**
     * 资源组加载出错
     * Resource group loading failed
     */
    private onResourceLoadError(event: RES.ResourceEvent): void {
        //TODO
        console.warn("Group:" + event.groupName + " has failed to load");
        this.onResourceLoadComplete(event);
    }
    /**
     * preload资源组加载进度
     * loading process of preload resource
     */
    private onResourceProgress(event: RES.ResourceEvent): void {
        if (event.groupName == "preload") {
            this.loadingView.setProgress(event.itemsLoaded, event.itemsTotal);
        }
    }

    private gameui: view.GameViewPlay
    private backhomeskin: view.GameViewBackHomePanel
    private ruleskin: view.GameViewGameRulePanel
    private soundskin: view.GameViewGameSoundPanel
    private tishiskin: view.GameViewGameTiShiPanel
    private joinroom: view.GameViewJoinRoomPanel
    private full: view.GameViewRoomFullPanel
    private win: view.GameJeSuanPanel
    private stageW: number;
    private stageH: number;
    private operation = window.sessionStorage.getItem("operation") ? window.sessionStorage.getItem("operation") : "JoinRoom"
    private if_full = window.sessionStorage.getItem("operation") ? true : false

    protected startCreateScene(): void {
        let sky = this.createBitmapByName("bg_png");
        this.addChild(sky);
        this.stageW = this.stage.stageWidth;
        this.stageH = this.stage.stageHeight;
        sky.width = this.stageW;
        sky.height = this.stageH;
        this.gameui = new view.GameViewPlay();
        this.ruleskin = new view.GameViewGameRulePanel()
        this.full = new view.GameViewRoomFullPanel();

        this.addChild(this.gameui);
        this.gameui.width = this.stageW;
        this.gameui.height = this.stageH;
        this.gameui.addEventListener("showtishi", this.onPlayGameTiShi, this);//提示弹窗
        this.gameui.addEventListener("showrule", this.onPlayGameRule, this);//规则弹窗
        this.gameui.addEventListener("backhome", this.onPlayGameGoHome, this);//返回首页弹窗
        this.gameui.addEventListener("showsound", this.onPlayGameSound, this);//声音设置弹窗
        this.gameui.addEventListener(view.GameViewPlay.ALERT_TIPS, this.onRoomTips, this);//出错消息
        this.gameui.addEventListener(view.GameViewPlay.JOIN_TIPS, this.onJoinRoomTips, this);//加入房间后将房间规则数据传给弹出加入询问面板
        this.gameui.addEventListener(view.GameViewPlay.CreateRoom, this.onGreatRoom, this);//创建房间
        this.gameui.addEventListener(view.GameViewPlay.JoinRoom, this.onJoinRoom, this);//加入房间后将房间规则数据传给规则和游戏面板
        this.gameui.addEventListener(view.GameViewPlay.Win, this.Win, this);//房间局数结束后进入排行榜

        this.ruleskin.visible = false;
        this.addChild(this.ruleskin);
    }
    private onRoomTips(e: egret.Event): void {
        this.addChild(this.full);
        this.full.width = this.stageW;
        this.full.height = this.stageH;
        this.full.setData(e.data);
        this.full.addEventListener("home", this.onPlayGameBackHome, this);
    }
    private onJoinRoomTips(e: egret.Event): void {
        this.joinroom = new view.GameViewJoinRoomPanel();
        this.addChild(this.joinroom);
        this.joinroom.width = this.stageW;
        this.joinroom.height = this.stageH;
        this.joinroom.setData(e.data);
       
    }
    private onGreatRoom(e: egret.Event): void {//将创建房间的数据传到规则面板和游戏面板
       
    }
    private Win(e: egret.Event): void {//房间局数结束后进入排行榜
       this.win = new view.GameJeSuanPanel();
       this.addChild(this.win);
       this.win.setData(e.data);

    }
    private onJoinRoom(e: egret.Event) {
        if (this.joinroom && this.joinroom.parent) {
            this.removeChild(this.joinroom)
        }
        this.gameui.setData(e.data);
    }
    private onPlayGameTiShi(e): void {//提示弹窗出现
        this.tishiskin = new view.GameViewGameTiShiPanel()
        if (!this.contains(this.tishiskin)) {
            this.addChild(this.tishiskin);
        }
        //this.tishiskin.width = this.stageW;
        //this.tishiskin.height = this.stageH;
        this.tishiskin.addEventListener("quxiaoskin", this.onPlayGameQuXiao, this);
    }
    private onPlayGameRule(e): void {//规则弹窗出现
        this.ruleskin.visible = true
        if (!this.contains(this.ruleskin)) {
            this.addChild(this.ruleskin);
        }
        this.ruleskin.width = this.stageW;
        this.ruleskin.height = this.stageH;
        this.ruleskin.addEventListener("quxiaoskin", this.onPlayGameQuXiao, this);
    }
    private onPlayGameGoHome(e): void {//返回首页弹窗出现
        this.backhomeskin = new view.GameViewBackHomePanel()
        if (!this.contains(this.backhomeskin)) {
            this.addChild(this.backhomeskin);
        }
        this.backhomeskin.width = this.stageW;
        this.backhomeskin.height = this.stageH;
        this.backhomeskin.addEventListener("quxiaoskin", this.onPlayGameQuXiao, this);
        this.backhomeskin.addEventListener("home", this.onPlayGameBackHome, this);
    }
    private onPlayGameSound(e): void {//声音设置弹窗出现
        this.soundskin = new view.GameViewGameSoundPanel()
        if (!this.contains(this.soundskin)) {
            this.addChild(this.soundskin);
        }
        this.soundskin.width = this.stageW;
        this.soundskin.height = this.stageH;
        this.soundskin.addEventListener("quxiaoskin", this.onPlayGameQuXiao, this);
    }
    private onPlayGameBackHome(e): void {//返回首页
        if (window["go"]) {
            window["go"]("http://www.kw08.cn/game.php/index/index69.html?url="+encodeURI(window.location.href));
        }
    }
    private onPlayGameQuXiao(e): void {//取消按钮，即留在房间游戏界面
        if (this.tishiskin && this.tishiskin.parent) {
            this.removeChild(this.tishiskin);
        }
        if (this.ruleskin && this.ruleskin.parent) {
            this.removeChild(this.ruleskin);
        }
        if (this.backhomeskin && this.backhomeskin.parent) {
            this.removeChild(this.backhomeskin);
        }
        if (this.soundskin && this.soundskin.parent) {
            this.removeChild(this.soundskin);
        }
    }
    private createBitmapByName(name: string): egret.Bitmap {
        let result = new egret.Bitmap();
        let texture: egret.Texture = RES.getRes(name);
        result.texture = texture;
        return result;
    }
}
